import { Inject, Injectable, NestMiddleware } from '@nestjs/common';
import { NextFunction, Response } from 'express';
import { FastifyRequest } from 'fastify';

import { LoggerService } from '../logger/logger.service';
import { getReqMainInfo } from './utils';

@Injectable()
export class LoggerMiddleware implements NestMiddleware {
  // 注入日志服务相关依赖
  @Inject(LoggerService)
  private readonly logger: LoggerService;

  use(req: FastifyRequest, res: Response, next: NextFunction) {
    // 记录日志
    const info = getReqMainInfo(req);
    this.logger.log(
      'route',
      `url: ${info.url},body: ${JSON.stringify(
        info.body || {},
      )},query: ${JSON.stringify(info.query || {})}`,
    );
    this.logger.log('route', info);

    next();
  }
}
